<?php
final class Main_Db
{
	/**
	 * @var string
	 */
	private static $_defaultUid = 'default';
	
	/**
	 * @var array
	 */
	private static $_adapters = array();
	
	/**
	 * @param string $adapterName
	 * @param array $config
	 * @return Main_Db_Adapter_Abstract
	 */
	public static function factory($adapterName, $config = array())
    {
        if (!is_array($config)) {
            throw new Exception('Adapter parameters must be in an array');
        }
        
        if (!is_string($adapterName) || empty($adapterName)) {
            throw new Exception('Adapter name must be specified in a string');
        }

		$adapterClassName = 'Main_Db_Adapter_' . $adapterName;        
        $dbAdapter = new $adapterClassName($config);
        self::$_adapters[self::$_defaultUid] = $dbAdapter; 

        if (! $dbAdapter instanceof Main_Db_Adapter_Abstract) {
            throw new Exception("Adapter class '$adapterClassName' does not extend Main_Db_Adapter_Abstract");
        }

        return $dbAdapter;
    }
    
    /**
     * @param string $uid
     * @return Main_Db_Adapter_Abstract
     */
    public static function get($uid = null) 
    {
    	if (null === $uid) {
    		$uid = self::$_defaultUid; 
    	} 
    	
    	if (array_key_exists($uid, self::$_adapters)) {
    		return self::$_adapters[$uid];
    	} else {
    		throw new Exception("Adapter class with uid '$uid' has not been initialized");
    	}
    }

}
